#import "XMAddressEditViewController.h"
#import <Masonry/Masonry.h>

// 定义表格单元格类型
typedef NS_ENUM(NSInteger, AddressEditCellType) {
    AddressEditCellTypeName,
    AddressEditCellTypePhone,
    AddressEditCellTypeRegion,
    AddressEditCellTypeDetailAddress,
    AddressEditCellTypeDefault,
    AddressEditCellTypeSaveButton
};

@interface XMAddressEditViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableDictionary *formData; // 表单数据
@property (nonatomic, strong) UIView *overlayView; // 遮罩视图

@end

@implementation XMAddressEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
//    self.view.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];

    // 初始化表单数据
    [self initializeFormData];
    
    // 设置UI
    [self setupUI];
}

- (void)initializeFormData {
    _formData = [NSMutableDictionary dictionary];
    
    if (_isEditMode && _addressData) {
        _formData[@"name"] = _addressData[@"name"];
        _formData[@"phone"] = _addressData[@"phone"];
        _formData[@"region"] = _addressData[@"region"];
        _formData[@"detailAddress"] = _addressData[@"detailAddress"];
        _formData[@"isDefault"] = _addressData[@"isDefault"];
    } else {
        _formData[@"name"] = @"";
        _formData[@"phone"] = @"";
        _formData[@"region"] = @"请选择省/市/区";
        _formData[@"detailAddress"] = @"";
        _formData[@"isDefault"] = @(NO);
    }
}

- (void)setupUI {
    // 创建遮罩视图
    _overlayView = [[UIView alloc] init];
    _overlayView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [_overlayView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(overlayTapped)]];
    [self.view addSubview:_overlayView];
    
    // 创建表格视图
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
//    _tableView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"AddressEditCell"];
    [self.view addSubview:_tableView];
    
    // 设置约束
    [_overlayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
  
    
    // 初始位置在屏幕下方
    _tableView.transform = CGAffineTransformMakeTranslation(0, 450);
    
    
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    saveButton.backgroundColor = [UIColor colorWithRed:0.92 green:0.23 blue:0.19 alpha:1.0];
    saveButton.layer.cornerRadius = 22;
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [saveButton setTitleColor:kColorHEX(0x333333) forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(saveButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveButton];
    
    
    CAGradientLayer *gradientLayer = [GradientHelper createGradientWithFrame:CGRectMake(0, 0, kScreenWidth, 44)
                                                                           startColor:kColorHEX(0xFFD800)
                                                                             endColor:kColorHEX(0xFFE44E)];
        
        // 将渐变图层添加到按钮的layer
    [saveButton.layer insertSublayer:gradientLayer atIndex:0];
    saveButton.layer.masksToBounds = YES;
 
    [saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.tableView.mas_bottom).offset(10);
//        make.left.equalTo(self.view).offset(15);
//        make.right.equalTo(self.view).offset(-15);
//        make.bottom.equalTo(self.view).offset(-10);
        
        make.left.equalTo(self.view).offset(28);
        make.right.equalTo(self.view).offset(-28);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-15);
        make.height.mas_equalTo(44);
    }];
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(kNavagationBarH+ kTabBarH);
        make.height.mas_equalTo(KScaleWidth(kScreentHeight-kNavagationBarH - kTabBarH)); // 表格高度
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    [self optimizeTableViewSpacing];
 
}
// 优化表格视图间距
- (void)optimizeTableViewSpacing {
    // 设置sectionHeader和sectionFooter的高度为接近0的值
    _tableView.sectionHeaderHeight = 0.01;
//    _tableView.sectionFooterHeight = 0.01;
    
    // 设置contentInset为负值来抵消顶部间距
    _tableView.contentInset = UIEdgeInsetsMake(-10, 0, 0, 0);
}


- (void)showInViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [viewController addChildViewController:self];
    [viewController.view addSubview:self.view];
    [self didMoveToParentViewController:viewController];
    
    if (animated) {
        [UIView animateWithDuration:0.3 animations:^{
            _tableView.transform = CGAffineTransformIdentity;
            _overlayView.alpha = 1.0;
        }];
    } else {
        _tableView.transform = CGAffineTransformIdentity;
        _overlayView.alpha = 1.0;
    }
}

- (void)dismissAnimated:(BOOL)animated {
    if (animated) {
        [UIView animateWithDuration:0.3 animations:^{
            _tableView.transform = CGAffineTransformMakeTranslation(0, 450);
            _overlayView.alpha = 0.0;
        } completion:^(BOOL finished) {
            [self willMoveToParentViewController:nil];
            [self.view removeFromSuperview];
            [self removeFromParentViewController];
        }];
    } else {
        [self willMoveToParentViewController:nil];
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }
}

- (void)overlayTapped {
    [self dismissAnimated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 4; // 姓名、电话、地区、详细地址
    } else {
        return 2; // 默认地址开关和保存按钮
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddressEditCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    AddressEditCellType cellType = [self cellTypeForIndexPath:indexPath];
    
    switch (cellType) {
        case AddressEditCellTypeName:
            [self configureNameCell:cell];
            break;
            
        case AddressEditCellTypePhone:
            [self configurePhoneCell:cell];
            break;
            
        case AddressEditCellTypeRegion:
            [self configureRegionCell:cell];
            break;
            
        case AddressEditCellTypeDetailAddress:
            [self configureDetailAddressCell:cell];
            break;
            
        case AddressEditCellTypeDefault:
            [self configureDefaultAddressCell:cell];
            break;
            
        case AddressEditCellTypeSaveButton:
            [self configureSaveButtonCell:cell];
            break;
    }
    
    return cell;
}

- (AddressEditCellType)cellTypeForIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0: return AddressEditCellTypeName;
            case 1: return AddressEditCellTypePhone;
            case 2: return AddressEditCellTypeRegion;
            case 3: return AddressEditCellTypeDetailAddress;
            default: return AddressEditCellTypeName;
        }
    } else {
        switch (indexPath.row) {
            case 0: return AddressEditCellTypeDefault;
            case 1: return AddressEditCellTypeSaveButton;
            default: return AddressEditCellTypeDefault;
        }
    }
}

- (void)configureNameCell:(UITableViewCell *)cell {
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"姓名";
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.textColor = kColorHEX(0x333333);
    [cell.contentView addSubview:titleLabel];
    
    UITextField *textField = [[UITextField alloc] init];
    textField.placeholder = @"请输入姓名";
    textField.font = [UIFont systemFontOfSize:16];
    textField.text = _formData[@"name"];
    textField.textColor = kColorHEX(0x333333);
    [self setTextField:textField placeholderColor:kColorHEX(0x999999)];

    textField.delegate = self;
    textField.tag = 100; // 姓名文本框tag
    [cell.contentView addSubview:textField];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(15);
        make.centerY.equalTo(cell.contentView);
    }];
    
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel.mas_right).offset(15);
        make.right.equalTo(cell.contentView).offset(-15);
        make.centerY.equalTo(cell.contentView);
    }];
}

- (void)configurePhoneCell:(UITableViewCell *)cell {
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"手机号码";
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.textColor = kColorHEX(0x333333);
    [cell.contentView addSubview:titleLabel];
    
    UITextField *textField = [[UITextField alloc] init];
    textField.placeholder = @"请输入手机号码";
    textField.font = [UIFont systemFontOfSize:16];
    [self setTextField:textField placeholderColor:kColorHEX(0x999999)];
    textField.keyboardType = UIKeyboardTypePhonePad;
    textField.text = _formData[@"phone"];
//    titleLabel.textColor = kColorHEX(0x333333);

    textField.delegate = self;
    textField.tag = 101; // 电话文本框tag
    [cell.contentView addSubview:textField];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(15);
        make.centerY.equalTo(cell.contentView);
    }];
    
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel.mas_right).offset(15);
        make.right.equalTo(cell.contentView).offset(-15);
        make.centerY.equalTo(cell.contentView);
    }];
}

- (void)configureRegionCell:(UITableViewCell *)cell {
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"所在地区";
    titleLabel.font = [UIFont systemFontOfSize:16];
    [cell.contentView addSubview:titleLabel];
    titleLabel.textColor = kColorHEX(0x333333);

    UILabel *regionLabel = [[UILabel alloc] init];
    regionLabel.text = _formData[@"region"];
    regionLabel.font = [UIFont systemFontOfSize:16];
    regionLabel.textColor = kColorHEX(0x999999);
    [cell.contentView addSubview:regionLabel];
//    [self setTextField:textField placeholderColor:kColorHEX(#999999)];

    UIImageView *arrowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_right"]];
    [cell.contentView addSubview:arrowImageView];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(15);
        make.centerY.equalTo(cell.contentView);
    }];
    
    [regionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel.mas_right).offset(15);
        make.right.equalTo(arrowImageView.mas_left).offset(-5);
        make.centerY.equalTo(cell.contentView);
    }];
    
    [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(cell.contentView).offset(-15);
        make.centerY.equalTo(cell.contentView);
        make.size.mas_equalTo(CGSizeMake(12, 12));
    }];
    
    // 添加点击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(regionCellTapped)];
    [cell.contentView addGestureRecognizer:tapGesture];
}

- (void)configureDetailAddressCell:(UITableViewCell *)cell {
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"详细地址";
    titleLabel.font = [UIFont systemFontOfSize:16];
    [cell.contentView addSubview:titleLabel];
    titleLabel.textColor = kColorHEX(0x333333);

    UITextField *textField = [[UITextField alloc] init];
    textField.placeholder = @"请输入街道、门牌号等详细地址";
    textField.font = [UIFont systemFontOfSize:16];
    [self setTextField:textField placeholderColor:kColorHEX(0x999999)];
    textField.text = _formData[@"detailAddress"];
    textField.delegate = self;
    textField.tag = 102; // 详细地址文本框tag
    [cell.contentView addSubview:textField];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(15);
        make.centerY.equalTo(cell.contentView);
    }];
    
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel.mas_right).offset(15);
        make.right.equalTo(cell.contentView).offset(-15);
        make.centerY.equalTo(cell.contentView);
    }];
}

- (void)configureDefaultAddressCell:(UITableViewCell *)cell {
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"设为默认地址";
    titleLabel.font = [UIFont systemFontOfSize:16];
    [cell.contentView addSubview:titleLabel];
    titleLabel.textColor = kColorHEX(0x333333);

    UISwitch *defaultSwitch = [[UISwitch alloc] init];
    [defaultSwitch setOn:[_formData[@"isDefault"] boolValue]];
    [defaultSwitch addTarget:self action:@selector(defaultSwitchChanged:) forControlEvents:UIControlEventValueChanged];
    [cell.contentView addSubview:defaultSwitch];
 
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(15);
        make.centerY.equalTo(cell.contentView);
    }];
    
    [defaultSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(cell.contentView).offset(-15);
        make.centerY.equalTo(cell.contentView);
    }];
}

- (void)configureSaveButtonCell:(UITableViewCell *)cell {
    // 清除默认内容
    for (UIView *subview in cell.contentView.subviews) {
        [subview removeFromSuperview];
    }
    
    // 创建保存按钮
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    saveButton.backgroundColor = [UIColor colorWithRed:0.92 green:0.23 blue:0.19 alpha:1.0];
    saveButton.layer.cornerRadius = 22;
    [saveButton setTitle:@"保存地址" forState:UIControlStateNormal];
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(saveButtonTapped) forControlEvents:UIControlEventTouchUpInside];
//    [cell.contentView addSubview:saveButton];
    
//    [saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(cell.contentView).offset(10);
//        make.left.equalTo(cell.contentView).offset(15);
//        make.right.equalTo(cell.contentView).offset(-15);
//        make.bottom.equalTo(cell.contentView).offset(-10);
//    }];
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    AddressEditCellType cellType = [self cellTypeForIndexPath:indexPath];
    
    if (cellType == AddressEditCellTypeSaveButton) {
        return 70; // 保存按钮行高
    } else {
        return 50; // 其他行高
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    AddressEditCellType cellType = [self cellTypeForIndexPath:indexPath];
    
    if (cellType == AddressEditCellTypeRegion) {
        [self regionCellTapped];
    }
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField *)textField {
    switch (textField.tag) {
        case 100: // 姓名
            _formData[@"name"] = textField.text;
            break;
            
        case 101: // 电话
            _formData[@"phone"] = textField.text;
            break;
            
        case 102: // 详细地址
            _formData[@"detailAddress"] = textField.text;
            break;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Actions

- (void)regionCellTapped {
    // 这里应该显示地区选择器，简化处理
    NSLog(@"地区选择器将在这里显示");
}

- (void)defaultSwitchChanged:(UISwitch *)sender {
    _formData[@"isDefault"] = @(sender.isOn);
}

- (void)saveButtonTapped {
    // 验证表单
    if ([_formData[@"name"] length] == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入姓名" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    if ([_formData[@"phone"] length] != 11) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入正确的手机号码" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    if ([_formData[@"region"] isEqualToString:@"请选择省/市/区"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择所在地区" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    if ([_formData[@"detailAddress"] length] == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入详细地址" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    // 保存地址
    if ([self.delegate respondsToSelector:@selector(addressEditController:didSaveAddress:)]) {
        [self.delegate addressEditController:self didSaveAddress:_formData];
    }
    
    // 关闭页面
    [self dismissAnimated:YES];
}


#pragma mark - Helper Methods

// 设置textField的placeholder颜色
- (void)setTextField:(UITextField *)textField placeholderColor:(UIColor *)color {
    if (textField.placeholder) {
        textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:textField.placeholder attributes:@{NSForegroundColorAttributeName: color}];
    }
}

@end
